# $Id: blog.py 33 2009-04-20 17:40:15Z fred1982 $
#

import os,re

from google.appengine.api import users

from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from google.appengine.api import memcache

import django
from django import http
from django import shortcuts
from django import template

# Model defined
class Entry(db.Model):
    name = db.StringProperty(required=True)
    giver = db.UserProperty()
    tags = db.CategoryProperty(required=False)
    category = db.CategoryProperty()
    recipient = db.StringProperty(required=False)
    description = db.TextProperty(required=True)
    url = db.StringProperty(required=False)
    type = db.IntegerProperty(default=1)
    comments = db.IntegerProperty(default=0)
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)

class Comment(db.Model):
    giver = db.UserProperty()
    content = db.TextProperty(required=False)
    reference = db.ReferenceProperty(Entry)
    created = db.DateTimeProperty(auto_now_add=True)
    active = db.BooleanProperty()

class EntryForm(djangoforms.ModelForm):
    class Meta:
        model = Entry
        exclude = ['giver', 'created', 'modified']

def respond(request, user, template, params=None):
    if params is None:
        params = {}
    if user:
        params['user'] = user
        params['sign_out'] = users.CreateLogoutURL('/')
        params['is_admin'] = (users.IsCurrentUserAdmin() or
                              'Dev' in os.getenv('SERVER_SOFTWARE'))
    else:
        params['sign_in'] = users.CreateLoginURL(request.path)
    if not template.endswith('.html'):
        template += '.html'
    return shortcuts.render_to_response(template, params)
        
def edit(request, entry_id):
    """Create or edit a entry. GET shows a blank form"""
    user = users.GetCurrentUser()
    if user is None:
        notice = 'Please Login First'
        return respond(request, user, 'notfound', {'notice': notice})
    if not users.is_current_user_admin():
        notice = 'Authorization Required'
        return respond(request, user, 'notfound', {'notice': notice})

    entry = None
    if entry_id:
        entry = Entry.get(db.Key.from_path(Entry.kind(), int(entry_id)))
        if entry is None:
            return respond(request, user, 'notfound')

    form = EntryForm(data=request.POST or None, instance=entry)
        
    if not request.POST:
        return respond(request, user, 'entry', {'form': form, 'entry': entry})

    errors = form.errors
    if not errors:
        try:
            entry = form.save(commit=False)
        except ValueError, err:
            errors['__all__'] = unicode(err)
    if errors:
        return respond(request, user, 'entry', {'form': form, 'entyr': entry})

    if not entry.giver:
        entry.giver = user
    entry.put()
    memcache.flush_all()
    
    return http.HttpResponseRedirect('/')

def index(request):
    """ Request / -- show all entries."""
    user = users.GetCurrentUser()
    if ('page' in request.GET):
        p = re.compile('^[0-9]+$')
        m = p.match(request.GET['page'])
        if m:
            if (int(request.GET['page']) > 66):
                page = 66
            else:
                page = int(request.GET['page'])
        else:
            page = 0
    else:
        page = 0
    data = memcache.get("list_" + str(page))
    if data is not None:
        entries = data
    else:
        entries = db.GqlQuery("SELECT * FROM Entry WHERE type = 1 ORDER By created DESC").fetch(15, offset = page*15)
        memcache.add("list_" + str(page), entries, 604800)
    entries_num = len(entries)
    if (entries_num == 0):
        return respond(request, user, 'notfound')
    else:
        return respond(request, user, 'list', {'entries': entries,'ppage':page+1,
                                           'npage':page-1,'list_num':len(entries)})

def new(request):
    return edit(request, None)

def view(request, entry_id=None):
    user = users.GetCurrentUser()
    entry = None
    if entry_id is None:
        urlPath = str(request.get_full_path())
        entry = db.GqlQuery("SELECT * FROM Entry WHERE type = 2 AND url = :1", urlPath).fetch(1)
        if (len(entry) == 0):
            return respond(request, user, 'notfound')
        else:
            return respond(request, user, 'view', {'entry': entry[0]})
    if entry_id:
        entry_data = memcache.get("entry_" + str(entry_id))
        if entry_data is not None:
            entry = entry_data
        else:
            entry = Entry.get(db.Key.from_path(Entry.kind(), int(entry_id)))
            if entry is None:
                return respond(request, user, 'notfound')
            else:
                memcache.add("entry_" + str(entry_id), entry, 604800)
        comments = db.GqlQuery("SELECT * FROM Comment WHERE reference=:1 ORDER BY created ASC", entry.key())
        if user is not None and request.POST:
            return post_comment(request, entry_id)
    return respond(request, user, 'view', {'entry': entry, 'comments': comments})

def post_comment(request, entry_id):
    entry = Entry.get(db.Key.from_path(Entry.kind(), int(entry_id)))
    comment = Comment()
    comment.reference = entry.key()
    comment.content = request.POST['comment'].decode("utf8") 
    comment.giver = users.get_current_user()
    comment.put()
    entry.comments += 1
    entry.put()
    return http.HttpResponseRedirect('/weblog/entry/%s' % entry_id)

def sitemap(request):
     entries = db.GqlQuery("SELECT * FROM Entry ORDER By created DESC")
     return respond(request, None, 'sitemap', {'entries': entries})

def logfeed(request):
    data = memcache.get("logfeed")
    if data is not None:
        entries = data
    else:
        entries = db.GqlQuery("SELECT * FROM Entry WHERE type=1 ORDER By created DESC").fetch(25)
        memcache.add("logfeed", entries, 604800)
    lastEntry = entries[0]
    return respond(request, None, 'logfeed', {'entries': entries, 'lastEntry':lastEntry})

def commentsfeed(request):
    return false
    
